/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eschool.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.eschool.model.Section;
import com.eschool.util.HibernateUtil;
import com.eschool.util.JdbcUtil;

/**
 * 
 * @author Ammar
 */

public class SectionDao {

	public static boolean addSection(Section section) {

		boolean isInserted = false;

		Connection connection = JdbcUtil.openConnection();

		try {
			CallableStatement storedProc = connection
					.prepareCall("{ call InsertSection(?,?,?) }");

			storedProc.setString(1, section.getSectionTitle());
			storedProc.setInt(2, section.getStrength());
			storedProc.setInt(3, section.getClas().getClassId());

			storedProc.execute();

			isInserted = true;
			connection.close();
		}

		catch (Exception e) {
			isInserted = false;
			connection.close();
			e.printStackTrace();
		} finally {
			return isInserted;
		}
	}

	public static Section getSectionByProperty(String property, Object value) {

		Session session = HibernateUtil.currentSession();

		Criteria crit = session.createCriteria(Section.class);
		crit.add(Restrictions.eq(property, value));

		Section section = (Section) crit.uniqueResult();

		HibernateUtil.closeSession(session);

		return section;
	}

	public static List getSections(int branchId) {

		Session session = HibernateUtil.currentSession();
		Criteria crit = session.createCriteria(Section.class); // .addOrder(Order.asc("strength"));

		crit.createAlias("clas", "c").createAlias("c.branch", "b");
		crit.add(Restrictions.eq("b.branchId", branchId));

		List sections = (List<Section>) crit.list();

		HibernateUtil.closeSession(session);

		if (sections == null)
			return Collections.EMPTY_LIST;

		return sections;
	}

	public static List getSections(Map<String, Object> conditions) {

		Session session = HibernateUtil.currentSession();
		Criteria crit = session.createCriteria(Section.class); // .addOrder(Order.asc("strength"));

		if (conditions != null)

			for (Iterator iterator = conditions.entrySet().iterator(); iterator
					.hasNext();) {

				Map.Entry condition = (Map.Entry) iterator.next();

				crit.add(Restrictions.eq(((String) condition.getKey()),
						condition.getValue()));
			}

		List sections = (List<Section>) crit.list();

		HibernateUtil.closeSession(session);

		if (sections == null)
			return Collections.EMPTY_LIST;

		return sections;
	}

	/*
	 * public static List<SaasAdmin> getAllSaasAdmin() { Session session =
	 * HibernateUtil.currentSession();
	 * 
	 * Criteria crit = session.createCriteria(SaasAdmin.class);
	 * 
	 * List admins = crit.list();
	 * 
	 * HibernateUtil.closeSession(session); return admins; }
	 */
}
